package itsm.isperp.module.service.slm;

import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.framework.data.dialect.DialectFactory;
import itsm.isperp.framework.service.BaseService;
import itsm.isperp.framework.web.response.ResultMessage;
import itsm.isperp.module.entity.slm.SlmServiceTarget;
import itsm.isperp.module.repository.slm.SlmServiceTargetMapper;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jdbc.support.DatabaseType;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

@Service
public class SlmServiceTargetService extends BaseService<SlmServiceTarget> {

	@Autowired
	protected SlmServiceTargetMapper slmServiceTargetMapper;

	@Autowired
	protected JdbcTemplate jdbcTemplate;

	@Override
	public SlmServiceTargetMapper getRepository() {
		return this.slmServiceTargetMapper;
	}

	@Override
	public ResultMessage delete(String id) {
		Assert.notNull(id, "id不能为空");

		SlmAlarmSettingService slmAlarmSettingService = ContextHolder
				.getSpringBean("slmAlarmSettingService");

		slmAlarmSettingService.deleteByServiceTargetId(id);

		this.getRepository().deleteByClass(id, SlmServiceTarget.class);
		return ResultMessage.success();
	}

	public void deleteByAgreementId(String agreementId) {

		Assert.notNull(agreementId, "agreementId不能为空");

		SlmAlarmSettingService slmAlarmSettingService = ContextHolder
				.getSpringBean("slmAlarmSettingService");

		slmAlarmSettingService.deleteByAgreementId(agreementId);
		this.getRepository().deleteByAgreementId(agreementId);
	}

	public void deleteByProjectId(String projectId) {
		Assert.notNull(projectId, "agreementId不能为空");

		SlmAlarmSettingService slmAlarmSettingService = ContextHolder
				.getSpringBean("slmAlarmSettingService");

		slmAlarmSettingService.deleteByProjectId(projectId);

		if (DialectFactory.getDatabaseType() == DatabaseType.MYSQL) {
			this.getRepository().deleteByProjectId(projectId);
		} else {
			String sql = "DELETE FROM slm_service_target WHERE id IN (SELECT a.id FROM slm_service_target a "
					+ "LEFT JOIN slm_service_agreement b ON a.agreement_id=b.id WHERE b.project_id='"
					+ projectId + "')";

			jdbcTemplate.execute(sql);
		}

	}

	/**
	 * 根据服务协议获取其对应的服务考核指标
	 * 
	 * @param serviceArgumentId
	 *            服务协议Id return 服务考核指标集合
	 */
	public List<SlmServiceTarget> findSlmServiceTargets(String agreementId) {
		return slmServiceTargetMapper
				.findSlmServiceTargetsByArgumentId(agreementId);
	}

	public List<Map<String, Object>> findSlmServiceTargetsValue(
			String argumentId, String objectId) {
		return slmServiceTargetMapper
				.findSlmServiceTargetsValueByArgumentIdAndObjectId(argumentId,
						objectId);
	}

}
